package com.example.dockerdemo.interceotor;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;

/**
 * @PACKAGE_NAME: com.example.dockerdemo.interceotor
 * @NAME: MyInterceotor
 * @description: 拦截器
 * @DATE: 2024/5/14
 * @USER: fz
 **/
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("================preHandle================");

        if (request.getMethod().equals("get")){
            String name = request.getParameter("name");
            if (name.equals("fz"))
            {
                System.out.println("preHandle==已放行");
                return true;
            }
            System.out.println("preHandle==已拦截");
            return false;
        }else if (request.getMethod().equals("post")){
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String requestBody = sb.toString();
            JSONObject jsonObject = JSONObject.parseObject(requestBody);
            String name = jsonObject.getString("name");
            if ("fz".equals(name)) {
                return true;
            }
            return false;
        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("================postHandle================");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("================afterCompletion================");
    }
}
